import re, uiautomation as auto
import sys

from PIL.SpiderImagePlugin import iforms

# def get_message_list(win):
#     """
#     占位实现：返回空列表，避免因缺少实现导致主流程中断。
#     后续可在此处使用 UIA 遍历窗口控件，采集聊天记录明细。
#     """
#     try:
#         print('get_message_detail.get_message_list: 使用占位实现', file=sys.stderr)
#         return []
#     except Exception as e:
#         print(f'get_message_detail.get_message_list 发生错误: {e}', file=sys.stderr)
#         return []

TITLE_PATTERNS = [r'.*BOSS直聘.*']            # 标题模糊匹配
CHROME_CLASSES = {'Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'}
MAX_DEPTH = 100
SEARCH_TMO = 3.0
PER_ITEM_TMO = 0.5

def list_top_windows():
    root = auto.GetRootControl()
    rows = []
    for w in root.GetChildren():
        try:
            rows.append((w.ControlTypeName, w.Name or '', w.ClassName or '', w))
        except Exception:
            pass
    for i, (t, n, c, _) in enumerate(rows, 1):
        print(f"{i:02d}. type={t:14} name='{n}' class='{c}'",file=sys.stderr)
    return rows

def name_matches(name: str) -> bool:
    return any(re.fullmatch(pat, name or '') for pat in TITLE_PATTERNS)


def get_boss_window(timeout: float = 3.0):
    """
    获取 BOSS直聘 根控件（WindowControl 或 PaneControl）
    :param timeout: 查找超时，秒
    :return: Control 对象或 None
    """
    with auto.UIAutomationInitializerInThread():
        auto.SetGlobalSearchTimeout(0.5)

        # 1) 先尝试 WindowControl（标准顶层窗口）
        win = auto.WindowControl(RegexName=r'.*BOSS直聘.*', searchDepth=1)
        if win.Exists(timeout, 0.2):
            return win

        # 2) 回退：在顶层 PaneControl 里找（Electron/Chromium 应用常见）
        root = auto.GetRootControl()
        for c in root.GetChildren():
            if 'BOSS直聘' in (c.Name or '') and c.ClassName in ('Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'):
                return c

    print("❌ 未找到 BOSS直聘 窗口",file=sys.stderr)

    return None


def pick_boss_root():
    """返回最合理的 BOSS 根节点（Window 或 Pane）"""
    # 1) 先尝试 WindowControl（如果 BOSS 是真正的顶层窗口）
    for pat in TITLE_PATTERNS:
        win = auto.WindowControl(RegexName=pat, searchDepth=1)
        if win.Exists(SEARCH_TMO, 0.2):
            return win

    # 2) 回退：在顶层子控件中找 PaneControl + Class=Chrome_WidgetWin_* + Name 匹配
    tops = list_top_windows()  # 也顺便打印出来方便你核对
    candidates = []
    for _, name, cls, elem in tops:
        if cls in CHROME_CLASSES and name_matches(name):
            candidates.append(elem)

    if candidates:
        # 取面积最大者作为根
        def area(e):
            try:
                r = e.BoundingRectangle
                return max(0, (r.right - r.left)) * max(0, (r.bottom - r.top))
            except Exception:
                return -1
        return max(candidates, key=area)

    return None


def get_all_texts(root_ctrl, max_depth=None):
    """
    遍历 root_ctrl 下的所有子孙，收集 Text/Document 控件的 Name
    """
    texts = []

    def walk(ctrl, depth=0):
        if max_depth is not None and depth > max_depth:
            return
        try:
            children = ctrl.GetChildren()
        except Exception:
            return
        for c in children:
            try:
                if c.ControlTypeName in ('TextControl', 'GroupControl'):
                    if c.Name:  # 去掉空
                        texts.append(c.Name.strip())
            except Exception:
                pass
            walk(c, depth+1)

    walk(root_ctrl)
    return texts

def is_visible(ctrl):
    try:
        if ctrl.IsOffscreen:
            return False
        r = ctrl.BoundingRectangle
        if r.right <= r.left or r.bottom <= r.top:
            return False
        # 判断是否在屏幕范围内
        from ctypes import windll
        sw = windll.user32.GetSystemMetrics(0)
        sh = windll.user32.GetSystemMetrics(1)
        if r.right <= 0 or r.bottom <= 0 or r.left >= sw or r.top >= sh:
            return False
        return True
    except Exception:
        return False

'''
['08-14 22:24', '8月14日 沟通的职位-品类运营']
['已读', '你好，还考虑新的机会吗？']
['此牛人近日被开聊较多，是否让您的消息', '？']


['08-15 03:58', '学历不行']

-------------------------------------------
时间： 08-14 22:24
['已读', '你好，还考虑新的机会吗？']


['08-15 03:58', '学历不行']


时间： 08-14 20:37
['请问品类运营还在招吗，谢谢！']

'''


def has_descendant_image(control):
    for child in control.GetChildren():
        if child.ControlTypeName == 'ImageControl':
            return True
        if has_descendant_image(child):  # 递归下去
            return True
    return False


def get_message_list(win):
    with auto.UIAutomationInitializerInThread():
        if win == None:
            win = get_boss_window()
        #win = get_boss_window()  # pick_boss_root()
        win.Exists(3, 0.2)  # 超时等待
        onlineResume = auto.HyperlinkControl(searchFromControl=win, Name='在线简历')
        parent = onlineResume.GetParentControl().GetParentControl()
        parent = parent.GetChildren()[1]

        first = auto.ListItemControl(searchFromControl=parent)
        children = first.GetParentControl().GetChildren()



        results = []
        firstHelloTime =  first.GetFirstChildControl().GetFirstChildControl().Name
        count = 1

        for child in children:



            if child.ControlTypeName == 'ListItemControl':


                # flag = False
                text = get_all_texts(child, 10)
                strText = str(text)

                #image = auto.ImageControl(searchFromControl=child)

                # 用法：传入你的 ListItemControl

                user_type = ''

                if has_descendant_image(child):

                    # print("包含 ImageControl")
                    user_type = 'not me'

                    # 是否是对方主动交换联系方式
                    # if '我想要和您交换联系方式，您是否同意' in text and '拒绝' in text and '同意' in text:
                    #     user_type = ''
                    # elif '对方想发送附件简历给您，您是否同意' in text and '拒绝' in text and '同意' in text:

                    if '拒绝' in text and '同意' in text:
                        user_type = ''
                    elif '点击预览附件简历' in text:
                        user_type = ''
                    elif '已发送简历' in text:
                        user_type = ''

                # else:
                #     print("不包含 ImageControl")

                # print('头像',image.Element != None)

                # print(strText)
                # if strText.__contains__("沟通的职位-") or strText.__contains__("已读") or strText.__contains__("送达"):
                #     flag = True
                # else:
                #     ListItemChildren = child.GetFirstChildControl().GetChildren()
                #     if len(ListItemChildren) == 2 or len(child.GetChildren()) == 2:
                #         flag = True
                #     else:
                #         for ListItemChild in ListItemChildren:
                #             if len(ListItemChild.GetChildren()) == 2:
                #                 flag = True
                #                 break
                #
                # if flag is False:
                #     continue

                if count == 1:
                    count += 1
                    continue
                else:
                    count += 1


                # print(text)
                # print('\n', file=sys.stderr)

                if not text or strText.__contains__('此牛人近日被开聊较多，是否让您的消息') or strText.__contains__('短信通知功能升级，增加真人顾问帮你要电话'):
                    continue

                time=''
                content = ''
                if len(text) == 2 and len(text[0]) > 2:
                    time = text[0]
                    content = text[1]
                elif len(text) == 1:
                    content = text[0]
                elif len(text) == 2 and len(text[0]) == 2:
                    content = text[1]

                if count == 3:
                    time =firstHelloTime


                messageState = ''
                #if text[0] == '送达' or text[0] == '已读' or strText == '送达' or strText == '已读':
                if strText.__contains__('送达') or strText.__contains__('已读'):
                    user_type = 'me'
                    messageState = text[0]

                if not content:
                    content = text

                result={
                    'time': time,
                    'content': content,
                    'type': user_type,
                    'messageState': messageState
                }
                results.append(result)

        return results



# print('开始执行')
# results = get_message_list(None)
# print(results)